import { Tree } from 'antd';
import type { DataNode } from 'antd/es/tree';
import { useEffect, useState } from 'react';
import type { Map } from 'maplibre-gl';

interface LayerTreeProps {
  mapRef: React.MutableRefObject<Map | null>;
}

const LayerTree = ({ mapRef }: LayerTreeProps) => {
  const [treeData, setTreeData] = useState<DataNode[]>([
    {
      title: '基础图层',
      key: 'base',
      children: [
        {
          title: 'OpenStreetMap',
          key: 'osm',
          isLeaf: true,
        },
      ],
    },
  ]);

  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>(['osm']);

  useEffect(() => {
    // 监听图层可见性变化
    if (!mapRef.current) return;

    checkedKeys.forEach((key) => {
      if (typeof key === 'string') {
        try {
          const layer = mapRef.current?.getLayer(key);
          if (layer) {
            mapRef.current?.setLayoutProperty(key, 'visibility', 'visible');
          }
        } catch (error) {
          console.warn(`Failed to get or update layer ${key}:`, error);
        }
      }
    });
  }, [checkedKeys, mapRef]);

  const onCheck = (checked: React.Key[] | { checked: React.Key[]; halfChecked: React.Key[] }) => {
    const checkedArray = Array.isArray(checked) ? checked : checked.checked;
    setCheckedKeys(checkedArray);
    // 更新图层可见性
    if (!mapRef.current) return;

    const allLayers = treeData.flatMap(node => node.children || []).map(child => child.key);
    allLayers.forEach((layerKey) => {
      if (typeof layerKey === 'string') {
        try {
          const visibility = checkedArray.includes(layerKey) ? 'visible' : 'none';
          mapRef.current?.setLayoutProperty(layerKey, 'visibility', visibility);
        } catch (error) {
          console.warn(`Failed to update layer ${layerKey} visibility:`, error);
        }
      }
    });
  };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ height: '35px', display: 'flex', alignItems: 'center', padding: '0 16px', borderBottom: '1px solid #f0f0f0', fontSize: '14px', color: '#333', fontWeight: 500 }}>
        图层管理
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: '8px' }}>
        <Tree
          checkable
          checkedKeys={checkedKeys}
          onCheck={onCheck}
          treeData={treeData}
          style={{ backgroundColor: 'transparent' }}
          className="custom-tree"
        />
      </div>
      <style>
        {`
          .custom-tree .ant-tree-node-content-wrapper {
            color: #333;
          }
          .custom-tree .ant-tree-checkbox-inner {
            background-color: transparent;
            border-color: #d9d9d9;
          }
          .custom-tree .ant-tree-checkbox-checked .ant-tree-checkbox-inner {
            background-color: #1677ff;
            border-color: #1677ff;
          }
          .custom-tree .ant-tree-node-content-wrapper:hover {
            background-color: #f5f5f5;
          }
          .custom-tree .ant-tree-treenode {
            padding: 4px 0;
          }
          .custom-tree .ant-tree-node-content-wrapper {
            padding: 2px 4px;
            border-radius: 4px;
          }
        `}
      </style>
    </div>
  );
};

export default LayerTree;